package com.github.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.config.WebServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.List;

/**
 * @author 陈敏
 * @version HistoryController.java, v 1.1 2021/5/26 23:00 chenmin Exp $
 * Created on 2021/5/26
 */
@RestController
@RequestMapping("/history")
public class HistoryController {

    @Autowired
    private WebServerProperties webServerProperties;

    @GetMapping("/history/{requestMethod}/{method}")
    public Object getHistoryMethod(@PathVariable("requestMethod") String requestMethod, @PathVariable("method") String method) {
        String jsonPath = webServerProperties.getJsonPath();
        String jsonFile = jsonPath.replace(new File(jsonPath).getName(), "") + StrUtil.SLASH + method + StrUtil.UNDERLINE + requestMethod + ".json";
        if (!FileUtil.exist(jsonFile)) {
            FileUtil.writeUtf8String("{}", jsonFile);
        }
        JSONObject jsonObject = JSONUtil.readJSONObject(new File(jsonFile), CharsetUtil.CHARSET_UTF_8);
        return jsonObject;
    }

    @DeleteMapping("/history/{requestMethod}/{method}")
    public Object deleteHistoryMethod(@PathVariable("requestMethod") String requestMethod, @PathVariable("method") String method) {
        String jsonPath = webServerProperties.getJsonPath();
        String jsonFile = jsonPath.replace(new File(jsonPath).getName(), "") + StrUtil.SLASH + method + StrUtil.UNDERLINE + requestMethod + ".json";
        if (FileUtil.exist(jsonFile)) {
            FileUtil.del(jsonFile);
        }
        return "OK";
    }

    @DeleteMapping("/clearAll")
    public Object clearAll() {
        String jsonPath = webServerProperties.getJsonPath();
        String jsonFileName = FileUtil.getName(jsonPath);
        String absolutePath = jsonPath.replace(jsonFileName, "");
        List<File> files = FileUtil.loopFiles(absolutePath, file -> file.getName().endsWith(".json") && !file.getName().endsWith(jsonFileName));
        files.forEach(File::deleteOnExit);
        return "OK";
    }

}
